package com.chang.dp.controller;

import com.chang.dp.daos.MessageDao;
import com.chang.dp.entity.MessageEntity;
import com.chang.dp.entity.MessageUserEntity;
import com.chang.dp.enumns.ErrorCodeEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jim.core.packets.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/messages")
@Api(tags = "未读信息")
public class MessageController {

    @Resource
    MessageDao messageDao;

    @Resource
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ApiOperation(value = "给离线用户发送信息")
    public HashMap<String, Object> sendMessage(@RequestBody MessageEntity messageEntity) {
        HashMap<String, Object> result = new HashMap<>();
        messageEntity.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        int rows = messageDao.addUnReadMessage(messageEntity);
        if (rows > 0) {
            result.put("code", ErrorCodeEnums.SUCCESS);
            result.put("message", "操作成功");
        } else {
            result.put("code", ErrorCodeEnums.DATA_ERR);
            result.put("message", "系统错误");
        }
        return result;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation("根据token查询未读信息")
    public HashMap<String, Object> getUnReadMessageList(@RequestHeader Map<String, String> headers) {
        HashMap<String, Object> result = new HashMap<>();
        String token = headers.get("token");
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (token != null && token.length() > 0) {
            User user = (User) valueOperations.get(token);
            if (user == null) {
                result.put("code", ErrorCodeEnums.AUTH_LATE);
                result.put("message", "登录过期,请重新登录");
                return result;
            }
            List<MessageUserEntity> list = messageDao.getUnReadMessagesByUserId(user.getUserId().toString());
            result.put("code", ErrorCodeEnums.SUCCESS);
            result.put("message", "查询成功");
            result.put("data", list);
            return result;
        }
        result.put("code", ErrorCodeEnums.AUTH_LATE);
        result.put("message", "登录过期,请重新登录");
        return result;

    }
}
